package com.egg.auth.controller.web;

import cn.dev33.satoken.oauth2.logic.SaOAuth2Handle;
import cn.dev33.satoken.oauth2.logic.SaOAuth2Template;
import cn.dev33.satoken.oauth2.logic.SaOAuth2Util;
import cn.dev33.satoken.oauth2.model.AccessTokenModel;
import com.egg.common.core.model.controller.WebController;
import com.egg.common.core.model.response.ResponseData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@Api(tags = WebController.API_PREFIX + "OAUTH2授权服务端中心")
@RestController
@RequestMapping("/oauth2")
public class WebOAuth2ServerController extends WebController {


    @Autowired
    private SaOAuth2Template saOAuth2Template;


    // 处理所有OAuth相关请求
    @RequestMapping("/*")
    public Object request() {
        return SaOAuth2Handle.serverRequest();
    }

    @ApiOperation(value = "accessToken获取用户信息")
    @GetMapping(value = "/userinfo")
    public ResponseData<AccessTokenModel> userInfo(
            @ApiParam(value = "accessToken", required = true) @RequestParam(value = "accessToken") String accessToken
    ) {
        // 检查域
        SaOAuth2Util.checkScope(accessToken, "userinfo");
        AccessTokenModel accessTokenModel = saOAuth2Template.getAccessToken(accessToken);
        if (null == accessTokenModel) {
            return ResponseData.error("accessToken无效");
        }
        return ResponseData.success(accessTokenModel);
    }


}